package tr.gov.tubitak.uekae.applet.light;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import tr.gov.tubitak.uekae.esya.api.common.crypto.BaseSigner;
import tr.gov.tubitak.uekae.esya.api.common.util.Base64;
import tr.gov.tubitak.uekae.esya.api.smartcard.signature.PKCS7Signature;

import java.io.ByteArrayOutputStream;
import java.security.cert.X509Certificate;

/**
 * Provides PKCS7 signature operations
 *
 * @author suleyman.uslu
 */
public class PKCS7Ops {

    private static final Logger msLogger = LoggerFactory.getLogger(PKCS7Ops.class);

    byte[] contentBytes;
    X509Certificate certificate;
    BaseSigner signer;

    /**
     * Constructor of PKCS7 type signature
     * @param aContentBytes    document to be signed
     * @param aCertificate     certificate to be added to signature
     * @param aSigner          signs the document
     */
    public PKCS7Ops(byte[] aContentBytes, X509Certificate aCertificate, BaseSigner aSigner) {

        contentBytes = aContentBytes;
        certificate = aCertificate;
        signer = aSigner;
    }

    /**
     * Creates PKCS7 signature, called from LightApplet
     * @return signature as byte array
     */
    public String sign() {

        ByteArrayOutputStream signature = new ByteArrayOutputStream();

        try {
            PKCS7Signature pkcs7Signature = new PKCS7Signature();

            pkcs7Signature.signInternalContent(contentBytes, certificate, signature, signer);
        }
        catch (Exception e) {

            msLogger.debug("Error in signing PKCS7", e);
        }

        byte[] signatureBytes = signature.toByteArray();
        msLogger.debug("signature: " + new String(signatureBytes));

        String s = Base64.encode(signatureBytes);

        return s;
    }

}
